import Vue from 'vue'
import Router from 'vue-router'
import config from "./config"
import {permission} from "../config";
// import


Vue.use(Router)

let ignore = ["login"]
let checkoutPermission = (path)=>{
    let userType = window.localStorage.getItem('userType')
    if(userType !== '0' && !userType){
        if(!ignore.includes(path)){
           return false
        }
    }else{
        if(permission.userType[userType].prohibition.includes(path)){
            return false
        }
    }
    return true
}

let before = (to, from, next) => {
    // to: Route: 即将要进入的目标 路由对象
    // from: Route: 当前导航正要离开的路由
    // next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。

    let isLogin = window.localStorage.getItem("token");  // 是否登录
    // 未登录状态；当路由到nextRoute指定页时，跳转至login
    if (!isLogin && !ignore.includes(to.name)) {
        next({name: 'login'})
    }
    if(!checkoutPermission(to.name)){
        next({name: 'login'})
    }


    next();
}
let after = (to, from) => {
   setTimeout(()=>{
       if(index.app.$store.state.pageOpenedList.includes(from.path) && !index.app.$store.state.cachePage.includes(from.name)){
           index.app.$store.commit('addCachePage',from.name)
       }
   },0)

}

let routerConfig = {
    routes: config.routes
}
let index = new Router(routerConfig)


export default index


// 全局路由守卫
index.beforeEach(before);
// 全局路由守卫
index.afterEach(after);


